PDF.js是一套由HTML建構的PDF閱讀器,由Mozilla Labs所推廣,目標是建立一個通用的PDF平台
GitHub Star: 20,000
Javascripting Overall: 94%
瀏覽器: Chrome、Firefox和IE10+
RWD: 不支援(可運作)
License: Apache-2.0
CDN
<!-- pdf.js v2.0.332 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.332/pdf.min.js"></script>
$ npm install pdfjs-dist
<script>
var url = "/cdn.mozilla.net/pdfjs/helloworld.pdf";
PDFJS.workerSrc = "//mozilla.github.io/pdf.js/build/pdf.worker.js";
var loadingTask = PDFJS.getDocument( url );
loadingTask.promise.then(
function( pdf ) {
console.log( "PDF loaded" );
var pageNumber = 1;
pdf.getPage(pageNumber).then( function( page ) {
console.log( "Page loaded" );
var scale = 1.5;
var viewport = page.getViewport( scale );
var canvas = document.getElementById( "example" );
var context = canvas.getContext( "2d" );
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render( renderContext );
renderTask.then( function () { console.log( "Page rendered" ); });
});
}, function ( reason ) {
console.error( reason );
}
);
</script>
<div>
<button id="prev">上一頁</button>
<button id="next">下一頁</button>
<span>頁數: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="example"></canvas>
<script>
// pdf檔案路徑,如果是絕對路徑,請Server使用CORS
var url = "//cdn.mozilla.net/pdfjs/tracemonkey.pdf";
PDFJS.workerSrc = "//mozilla.github.io/pdf.js/build/pdf.worker.js";
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 0.8,
canvas = document.getElementById( "example" ),
ctx = canvas.getContext( "2d" );
function renderPage( num )
{
pageRendering = true;
pdfDoc.getPage( num ).then( function( page ) {
var viewport = page.getViewport( scale );
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then( function() {
pageRendering = false;
if ( pageNumPending !== null ) {
renderPage( pageNumPending );
pageNumPending = null;
}
});
});
document.getElementById( "page_num" ).textContent = num;
}
function queueRenderPage( num )
{
if ( pageRendering ) {
pageNumPending = num;
} else {
renderPage( num );
}
}
function onPrevPage()
{
// 上一頁
if ( pageNum <= 1 ) {
return;
}
pageNum--;
queueRenderPage( pageNum );
}
document.getElementById( "prev" ).addEventListener( "click", onPrevPage );
function onNextPage()
{
// 下一頁
if ( pageNum >= pdfDoc.numPages ) {
return;
}
pageNum++;
queueRenderPage( pageNum );
}
document.getElementById( "next" ).addEventListener( "click", onNextPage );
PDFJS.getDocument( url ).then( function( pdfDoc_ ) {
pdfDoc = pdfDoc_;
document.getElementById( "page_count" ).textContent = pdfDoc.numPages;
renderPage( pageNum );
});
</script>